<template>
  <el-button
    :size="size"
    :type="type"
    :icon="icon"
    :loading="downloading"
    @click="onDownload"
  >{{ buttonLabel }}</el-button>
</template>

<script>
import fileDownload from 'js-file-download'
import Download from '@/api/download'
import { matchContentDispositionFilename } from '@/utils'
export default {
  name: 'DownloadButton',
  props: {
    text: {
      type: String,
      default: '下载'
    },
    showText: {
      type: Boolean,
      default: true
    },
    icon: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: ''
    },
    size: {
      type: String,
      default: 'small'
    },
    url: {
      type: String,
      required: true
    },
    params: {
      type: Object,
      default: null
    },
    filename: {
      type: String,
      default: ''
    },
    format: {
      type: String,
      default: 'xlsx'
    }
  },
  data() {
    return {
      downloading: false
    }
  },
  computed: {
    saveFileName() {
      var prefix = this.$moment()
        .locale('zh-cn')
        .format('ll')
      var fileNames = this.filename.split('.')
      var ext = this.format
      if (fileNames.length > 1) {
        ext = fileNames.pop().toLowerCase()
      }
      var filename = fileNames.pop()
      return `${prefix}-${filename}.${ext}`
    },
    buttonLabel() {
      if (this.showText && this.text) {
        return this.text
      }
      return undefined
    }
  },
  methods: {
    onDownload() {
      console.log('params', this.params)
      console.log('saveFileName', this.saveFileName)
      this.downloadStream(this.url, this.saveFileName, this.params)
    },
    downloadStream(url, name, params) {
      this.downloading = true
      var stream = new Download(url)
      stream
        .download(params)
        .then(res => {
          if (!res) {
            return
          }
          console.log('Res::::::', res)
          const { headers, data } = res
          fileDownload(data, this.bindFileName(name, headers))
          this.downloading = false
        })
        .catch(err => {
          console.log('[POST reject Error]', err)
          this.$message({
            message: err.msg,
            type: 'error'
          })
          this.downloading = false
        })
    },
    bindFileName(name, headers) {
      console.log('headers', headers)
      return matchContentDispositionFilename(headers) || name
    }
  }
}
</script>

